import { bus } from "@/bus";
import { loadConfig } from '@/config.ts'
import * as state from '../state'
import { createWbHistory } from "./wristbandHistory";
import { DataSource } from "typeorm";
import { Wristband } from "@/entity/wristband.entity";
import { WristbandHistory } from "@/entity/wristband_history.entity";

export async function setup(AppDataSource: DataSource | null) {
    let conf = await loadConfig()
    const wristbandHistoryRepo = AppDataSource ? AppDataSource.getRepository(WristbandHistory) : null
    const wristbandRepo = AppDataSource ? AppDataSource.getRepository(Wristband) : null
    // 订阅数据
    bus.on('wb.adv.decode', async (pack: any) => {

        // console.log(pack)

        // @todo 写入数据库 历史数据表
        const gw = {
            mac: pack.mac,
            version_bin: pack.frm_ver.split('/')[0], // 固件版本号
            version_fs: pack.frm_ver.split('/')[1], // 文件系统版本号
            time: new Date(),
            last_report_time: new Date(), // 最后上报广播数据的时间
            last_report_wb_cnt: pack.wb_adv.length, // 最后上报手环数据
            deleted: false,
            outdoor: false,

        }
        const wbArray = pack.wb_adv.map((item: any) => {
            return {
                addr: item.mac.toUpperCase(),
                rssi: item.rssi | 1000000000,
                idx: item.idx,
                beacon1: item.beacon1,
                beacon2: item.beacon2,
                beacon3: item.beacon3,
                acc_x: 0,
                acc_y: 0,
                acc_z: 0,
                steps: item.steps,
                hr: item.hr,
                hrv: item.hrv,
                hr_confidence: item.hr_confidence,
                temperature: item.temp,
                bat_vol: item.bat_vol,
                charging: item.charging,
                wear_on: item.wear_on,
                req_rt: item.req_rt,
                fake_hr: item.fake_hr,
                time: new Date(),
                motion: item.motion || 0, // 运动强度
                motion_variance: item.motion_variance || 0, // 运动方差
                format: item.format_ver,
                version: item.firmware_ver,
                name: 'c1',
                deleted: false,
            }
        })
        // 只有在 AppDataSource 存在时才进行数据库操作
        if (AppDataSource) {
            for (const item of wbArray) {
                // 更新手环实时数据表 和 手环最后一组实时数据表
                await updateWristbandHistory(gw, item);
            }
        } else {
            // console.log('AppDataSource is null, skipping database updates');
        }



        async function updateWristbandHistory(gw: state.GwObject, val: state.WbArray) {
            // console.log('wbArray', wbArray)
            // 保存至数据库 (wristbandAdv, wristbandLastAdv)
            // 如果 AppDataSource 存在，则保存至数据库
            if (AppDataSource) {
                await createWbHistory(gw.mac, val.addr.toUpperCase(), val.rssi || -1000000, val, val.format || 111111, new Date(), wristbandRepo, wristbandHistoryRepo);
            } else {
                // console.log('AppDataSource is null, skipping wristband history update');
            }
        }

    })
}